import 'dart:io';
import 'package:cult/function/utils/open_url.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'post_publish_controller.dart';
import '../../../function/model/post_model.dart';
import '../../../function/utils/my_common.dart';

/// 发布帖子页面
class PostPublishPage extends GetView<PostPublishController> {
  const PostPublishPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PostPublishController>(
      init: PostPublishController(),
      builder: (controller) {
        return Scaffold(
          backgroundColor: Colors.transparent,
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/home_bg.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 返回按钮
                    _buildBackButton(),
                    SizedBox(height: 20.h),

                    // 资源选择区域
                    _buildResourceSelection(controller),
                    SizedBox(height: 24.h),

                    // 标题输入
                    _buildTitleInput(controller),
                    SizedBox(height: 20.h),

                    // 内容输入
                    _buildContentInput(controller),
                    SizedBox(height: 24.h),

                    // 分类选择
                    _buildCategorySelection(controller),
                    SizedBox(height: 20.h),

                    // 标签管理
                    _buildLabelManagement(controller),
                    SizedBox(height: 16.h),

                    // EULA链接
                    _buildEulaLink(),
                    SizedBox(height: 16.h),
                    // 发布按钮
                    _buildPublishButton(controller),

                    SizedBox(height: 40.h),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建返回按钮
  Widget _buildBackButton() {
    return GestureDetector(
      onTap: () => Get.back(),
      child: Container(
        width: 40.w,
        height: 40.w,
        decoration: BoxDecoration(
          color: MyCommonUtils.white.withOpacity(0.2),
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Icon(
          Icons.arrow_back_ios_new,
          color: MyCommonUtils.white,
          size: 20.sp,
        ),
      ),
    );
  }

  /// 构建资源选择区域
  Widget _buildResourceSelection(PostPublishController controller) {
    return Obx(() {
      final asset = controller.selectedAsset.value;

      return GestureDetector(
        onTap: controller.selectResource,
        child: Container(
          width: double.infinity,
          height: 200.h,
          decoration: BoxDecoration(
            color: MyCommonUtils.white,
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(
              color: MyCommonUtils.grey.withOpacity(0.3),
              width: 1,
            ),
          ),
          child:
              asset != null
                  ? _buildSelectedResource(asset)
                  : _buildResourcePlaceholder(),
        ),
      );
    });
  }

  /// 构建资源占位符
  Widget _buildResourcePlaceholder() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(Icons.camera_alt_outlined, size: 48.sp, color: MyCommonUtils.grey),
        SizedBox(height: 12.h),
        Text(
          'Add photos, videos',
          style: TextStyle(
            fontSize: 16.sp,
            color: MyCommonUtils.grey,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  /// 构建已选择的资源
  Widget _buildSelectedResource(asset) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12.r),
      child: Stack(
        children: [
          // 资源预览
          Positioned.fill(
            child:
                asset.type == AssetType.video
                    ? FutureBuilder<String?>(
                      future: _generateVideoThumbnail(asset),
                      builder: (context, snapshot) {
                        if (snapshot.connectionState ==
                            ConnectionState.waiting) {
                          return Container(
                            color: MyCommonUtils.grey.withOpacity(0.3),
                            child: Center(
                              child: CircularProgressIndicator(
                                color: MyCommonUtils.orange,
                              ),
                            ),
                          );
                        }

                        if (snapshot.hasData && snapshot.data != null) {
                          try {
                            return Image.file(
                              File(snapshot.data!),
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                print('Error loading thumbnail image: $error');
                                return Container(
                                  color: MyCommonUtils.grey.withOpacity(0.3),
                                  child: Icon(
                                    Icons.videocam,
                                    size: 48.sp,
                                    color: MyCommonUtils.grey,
                                  ),
                                );
                              },
                            );
                          } catch (e) {
                            print('Exception loading thumbnail: $e');
                            return Container(
                              color: MyCommonUtils.grey.withOpacity(0.3),
                              child: Icon(
                                Icons.videocam,
                                size: 48.sp,
                                color: MyCommonUtils.grey,
                              ),
                            );
                          }
                        }

                        return Container(
                          color: MyCommonUtils.grey.withOpacity(0.3),
                          child: Icon(
                            Icons.videocam,
                            size: 48.sp,
                            color: MyCommonUtils.grey,
                          ),
                        );
                      },
                    )
                    : AssetEntityImage(
                      asset,
                      fit: BoxFit.cover,
                      isOriginal: false,
                    ),
          ),

          // 视频播放图标
          if (asset.type == AssetType.video)
            Center(
              child: Container(
                width: 60.w,
                height: 60.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.6),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.play_arrow,
                  color: MyCommonUtils.white,
                  size: 32.sp,
                ),
              ),
            ),

          // 删除按钮
          Positioned(
            top: 8.h,
            right: 8.w,
            child: GestureDetector(
              onTap: () => controller.selectedAsset.value = null,
              child: Container(
                width: 24.w,
                height: 24.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.6),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.close,
                  color: MyCommonUtils.white,
                  size: 16.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建标题输入
  Widget _buildTitleInput(PostPublishController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Caption',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: MyCommonUtils.white,
            fontFamily: GoogleFonts.berkshireSwash().fontFamily,
          ),
        ),
        SizedBox(height: 12.h),
        Container(
          decoration: BoxDecoration(
            color: MyCommonUtils.white,
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: TextField(
            controller: controller.titleController,
            decoration: InputDecoration(
              hintText: 'Please Enter The Title',
              hintStyle: TextStyle(color: MyCommonUtils.grey, fontSize: 16.sp),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(16.w),
            ),
            style: TextStyle(fontSize: 16.sp, color: MyCommonUtils.black),
          ),
        ),
      ],
    );
  }

  /// 构建内容输入
  Widget _buildContentInput(PostPublishController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Element',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: MyCommonUtils.white,
            fontFamily: GoogleFonts.berkshireSwash().fontFamily,
          ),
        ),
        SizedBox(height: 12.h),
        Container(
          decoration: BoxDecoration(
            color: MyCommonUtils.white,
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: TextField(
            controller: controller.contentController,
            maxLines: 6,
            decoration: InputDecoration(
              hintText: 'Please Enter Content',
              hintStyle: TextStyle(color: MyCommonUtils.grey, fontSize: 16.sp),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(16.w),
            ),
            style: TextStyle(fontSize: 16.sp, color: MyCommonUtils.black),
          ),
        ),
      ],
    );
  }

  /// 构建分类选择
  Widget _buildCategorySelection(PostPublishController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Event Tags',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: MyCommonUtils.white,
            fontFamily: GoogleFonts.berkshireSwash().fontFamily,
          ),
        ),
        SizedBox(height: 12.h),
        Obx(
          () => Wrap(
            spacing: 8.w,
            runSpacing: 8.h,
            children:
                PostCategory.values.map((category) {
                  final isSelected =
                      controller.selectedCategory.value == category;
                  return GestureDetector(
                    onTap: () => controller.selectCategory(category),
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 8.h,
                      ),
                      decoration: BoxDecoration(
                        color:
                            isSelected
                                ? MyCommonUtils.orange
                                : MyCommonUtils.white,
                        borderRadius: BorderRadius.circular(20.r),
                        border:
                            isSelected
                                ? null
                                : Border.all(
                                  color: MyCommonUtils.black,
                                  width: 1,
                                ),
                      ),
                      child: Text(
                        '# ${category.displayName}',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                          color:
                              isSelected
                                  ? MyCommonUtils.white
                                  : MyCommonUtils.black,
                        ),
                      ),
                    ),
                  );
                }).toList(),
          ),
        ),
      ],
    );
  }

  /// 构建标签管理
  Widget _buildLabelManagement(PostPublishController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Add Labels',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: MyCommonUtils.white,
            fontFamily: GoogleFonts.berkshireSwash().fontFamily,
          ),
        ),
        SizedBox(height: 12.h),

        // 已选择的标签
        Obx(
          () => Wrap(
            spacing: 8.w,
            runSpacing: 8.h,
            children: [
              ...controller.selectedLabels.map(
                (label) => Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color: MyCommonUtils.orange,
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        '# $label',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                          color: MyCommonUtils.white,
                        ),
                      ),
                      SizedBox(width: 4.w),
                      GestureDetector(
                        onTap: () => controller.removeLabel(label),
                        child: Icon(
                          Icons.close,
                          size: 16.sp,
                          color: MyCommonUtils.white,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              // 添加标签按钮
              if (controller.selectedLabels.length < 5)
                GestureDetector(
                  onTap: () => _showLabelPicker(controller),
                  child: Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: MyCommonUtils.white,
                      shape: BoxShape.circle,
                      border: Border.all(color: MyCommonUtils.black, width: 1),
                    ),
                    child: Icon(
                      Icons.add,
                      size: 20.sp,
                      color: MyCommonUtils.black,
                    ),
                  ),
                ),
            ],
          ),
        ),

        // 标签计数
        SizedBox(height: 8.h),
        Obx(
          () => Text(
            '${controller.selectedLabels.length}/5',
            style: TextStyle(
              fontSize: 12.sp,
              color: MyCommonUtils.white.withOpacity(0.8),
            ),
          ),
        ),
      ],
    );
  }

  /// 显示标签选择器
  void _showLabelPicker(PostPublishController controller) {
    Get.bottomSheet(
      Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          color: MyCommonUtils.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.r),
            topRight: Radius.circular(20.r),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Select Labels',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: MyCommonUtils.black,
              ),
            ),
            SizedBox(height: 16.h),
            Obx(
              () => Wrap(
                spacing: 8.w,
                runSpacing: 8.h,
                children:
                    controller.availableLabels.map((label) {
                      final isSelected = controller.selectedLabels.contains(
                        label,
                      );
                      return GestureDetector(
                        onTap: () {
                          if (isSelected) {
                            controller.removeLabel(label);
                          } else if (controller.selectedLabels.length < 5) {
                            controller.addLabel(label);
                          }
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 16.w,
                            vertical: 8.h,
                          ),
                          decoration: BoxDecoration(
                            color:
                                isSelected
                                    ? MyCommonUtils.orange
                                    : MyCommonUtils.white,
                            borderRadius: BorderRadius.circular(20.r),
                            border: Border.all(
                              color: MyCommonUtils.black,
                              width: 1,
                            ),
                          ),
                          child: Text(
                            '# $label',
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w600,
                              color:
                                  isSelected
                                      ? MyCommonUtils.white
                                      : MyCommonUtils.black,
                            ),
                          ),
                        ),
                      );
                    }).toList(),
              ),
            ),
            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }

  /// 构建发布按钮
  Widget _buildPublishButton(PostPublishController controller) {
    return Obx(
      () => Container(
        height: 56.h,
        padding: EdgeInsets.symmetric(horizontal: 60.w),
        decoration: BoxDecoration(
          color: MyCommonUtils.orange,
          borderRadius: BorderRadius.circular(28.r),
        ),
        child:
            controller.isPublishing.value
                ? SizedBox(
                  width: 24.w,
                  height: 24.w,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor: AlwaysStoppedAnimation<Color>(
                      MyCommonUtils.white,
                    ),
                  ),
                )
                : Image.asset(
                  'assets/images/send_button.png',
                  width: 24.w,
                  height: 24.w,
                ),
      ).alignCenter().inkWell(
        onTap: () {
          if (!controller.isPublishing.value) {
            controller.publishPost();
          }
        },
      ),
    );
  }

  /// 构建EULA链接
  Widget _buildEulaLink() {
    return Center(
      child: GestureDetector(
        onTap: () {
          CultUtils.openEula();
        },
        child: Text(
          'EULA',
          style: TextStyle(
            fontSize: 14.sp,
            color: MyCommonUtils.white,
            decoration: TextDecoration.underline,
            decorationColor: MyCommonUtils.white,
            fontWeight: FontWeight.w700,
          ),
        ),
      ),
    );
  }

  /// 生成视频缩略图
  Future<String?> _generateVideoThumbnail(AssetEntity asset) async {
    try {
      final File? file = await asset.file;
      if (file == null) {
        print('Asset file is null');
        return null;
      }

      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String thumbnailDir = path.join(appDocDir.path, 'thumbnails');

      // 确保目录存在
      await Directory(thumbnailDir).create(recursive: true);

      // 生成唯一文件名
      final String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
      final String thumbnailFileName = 'thumb_$timestamp.jpg';
      final String thumbnailPath = path.join(thumbnailDir, thumbnailFileName);

      print('Generating thumbnail for video: ${file.path}');
      print('Thumbnail will be saved to: $thumbnailPath');

      // 生成缩略图
      final String? thumbnail = await VideoThumbnail.thumbnailFile(
        video: file.path,
        thumbnailPath: thumbnailPath,
        imageFormat: ImageFormat.JPEG,
        quality: 75,
        maxHeight: 200,
      );

      if (thumbnail != null) {
        print('Thumbnail generated successfully: $thumbnail');
        return thumbnail;
      } else {
        print('Thumbnail generation failed');
        return null;
      }
    } catch (e) {
      print('Error generating video thumbnail: $e');
      return null;
    }
  }
}
